package com.bauer.java.spring.transaction.programmtic;

import com.bauer.java.spring.transaction.mapper.BaseMenuMapper;
import com.bauer.java.spring.transaction.model.po.BaseMenu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @Author ：rui.wei
 * @Date ：Created in 17:02 2019/7/3
 * @Description： 编程式事物
 *
 * 1、使用transactionManager 做事物控制    需要手动开启和关闭事物
 * 2、使用PlatformTransactionManager 做事物控制   只需要执行execute 方法
 */
@Service
public class ProgrammaticTransactionDemo {


    @Autowired
    private BaseMenuMapper baseMenuMapper;

    @Autowired
    private TransactionTemplate transactionTemplate;


    @Autowired
    private PlatformTransactionManager transactionManager;

    public void userTransactionManager() {
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setName("SomeTxName");
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            BaseMenu baseMenu = new BaseMenu();
            baseMenu.setMenuName("menu1");
            baseMenu.setMenuMemo("Programmatic");
            baseMenuMapper.insert(baseMenu);
            //这时事物已提交 数据已经可以在数据库中查看到
            System.out.println("menu saved");
        } catch (Exception ex) {
            ex.printStackTrace();
            transactionManager.rollback(status);
        }
        transactionManager.commit(status);
    }


    public void userTransactionTemplate() {
        transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        transactionTemplate.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus status) {
                BaseMenu baseMenu = new BaseMenu();
                baseMenu.setMenuName("menu1 userTransactionTemplate");
                baseMenu.setMenuMemo("Programmatic");
                baseMenuMapper.insert(baseMenu);
                //这时事物已提交 数据已经可以在数据库中查看到
                System.out.println("menu saved");

                return null;
            }
        });
    }

}
